from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from core.base.orm_model import Base
from config.config import settings
from urllib.parse import quote_plus

# 对密码进行 URL 编码
encoded_password = quote_plus(settings.MYSQL_PASSWORD)

SQLALCHEMY_DATABASE_URL = f"mysql+asyncmy://{settings.MYSQL_USER}:{encoded_password}@{settings.MYSQL_HOST}:{settings.MYSQL_PORT}/{settings.MYSQL_DATABASE}"

# 添加连接池配置
engine = create_async_engine(
    SQLALCHEMY_DATABASE_URL,
    echo=settings.SQL_ECHO,
    pool_size=20,  # 连接池大小
    max_overflow=10,  # 最大溢出连接数
    pool_timeout=30,  # 连接池超时时间
    pool_recycle=1800,  # 连接回收时间（30分钟）
    pool_pre_ping=True,  # 启用连接健康检查
)

# 创建异步会话工厂
AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)


# 获取数据库会话的依赖注入函数
async def get_db():
    """获取数据库会话"""
    async with AsyncSessionLocal() as session:
        try:
            yield session
        finally:
            await session.close()